package com.kelvin.retrofitrxdemo;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private ImageView iv;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

// 4.4及以上版本开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {

        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setNavigationBarTintEnabled(true);
        // 自定义颜色
        tintManager.setTintColor(Color.parseColor("#ffffff"));


        //        doRetrofitRequest();
//        doRx();
//        doRx2();
//        doRx3();
//        doRx4();
//        doRx5();
//        doRx6();
//        doRx7();
        doRetroRequestWithRxJava();
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }


    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * rx转换6 无序传输
     */
    private void doRx6() {

        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                e.onNext(1);
                e.onNext(2);
                e.onNext(3);
            }
        }).concatMap(new Function<Integer, ObservableSource<String>>() {
            @Override
            public ObservableSource<String> apply(Integer integer) throws Exception {
                List<String> list = new ArrayList<String>();
                for (int i = 0; i < 3; i++) {
                    list.add("i am value:" + integer);
                }
                return Observable.fromIterable(list).delay(10, TimeUnit.MILLISECONDS);
            }
        }).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.d("flatmap:", s);
            }
        });

    }

    /**
     * rx的转换
     */
    private void doRx5() {

        Student.Course course1 = new Student.Course();
        course1.setName("math");
        Student.Course course2 = new Student.Course();
        course2.setName("bio");
        Student.Course course3 = new Student.Course();
        course3.setName("art");

        List<Student.Course> courses = new ArrayList<>();
        courses.add(course1);
        courses.add(course2);
        courses.add(course3);

        Student st1 = new Student();
        st1.setCourses(courses);
        Student st2 = new Student();
        st2.setCourses(courses);
        Student[] students = {st1, st2};

        Observable.fromArray(students).flatMap(new Function<Student, ObservableSource<Student.Course>>() {
            @Override
            public ObservableSource<Student.Course> apply(Student student) throws Exception {
                return Observable.fromIterable(student.getCourses());
            }
        }).subscribe(new Consumer<Student.Course>() {
            @Override
            public void accept(Student.Course course) throws Exception {
                //如果为空的话就不打印
                Log.d("flat map:", course.getName());
            }
        });

    }

    /**
     * rx的线程切换 observeOn是指定回调发生在
     */
    private void doRx2() {
        new Thread() {
            @Override
            public void run() {
                Observable.just(1, 2, 3, 4).subscribeOn(Schedulers.io()).
                        subscribe(new Observer<Integer>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                                //TODO 这个方法都在主线程订阅
                                Log.d("onSubscribe", "onSubscribe thread:" + Thread.currentThread().getId());
                            }

                            @Override
                            public void onNext(Integer value) {
                                Log.d("onNext", "onNext thread:" + Thread.currentThread().getId());
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {
                                Log.d("onComplete", "onComplete thread:" + Thread.currentThread().getId());
                            }
                        });
            }
        }.run();
    }

    /**
     * 使用rxjava
     */
    private void doRx() {
        //创建一个上游
        Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                e.onNext(1);
                e.onNext(2);
                e.onNext(3);
                e.onComplete();
            }

        });
        //创建一个下游 observer
        Observer<Integer> observer = new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.d(TAG, "subscribe");
            }

            @Override
            public void onNext(Integer value) {
                Log.d(TAG, "" + value);
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "error");
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "complete");
            }
        };
        //建立连接
        observable.subscribe(observer);
    }

    /**
     * 使用retrofit做请求
     */
    private void doRetrofitRequest() {

//        String api_base_url = "https://api.github.com/";
//        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
//        OkHttpClient okHttpClient = httpClientBuilder.build();
//        Retrofit.Builder builder = new Retrofit.Builder().baseUrl(api_base_url).addConverterFactory(
//                GsonConverterFactory.create()
//        );
//        Retrofit retrofit = builder.client(okHttpClient).build();
//        GitHubClient gitHubClient = retrofit.create(GitHubClient.class);
        Call<List<GitHubRepo>> call =
                ServiceGenerator.createService(GitHubClient.class).reposForUser("fs-opensource");


        /**
         * 将call enqueue就会运行
         */
        call.enqueue(new Callback<List<GitHubRepo>>() {
            @Override
            public void onResponse(Call<List<GitHubRepo>> call, Response<List<GitHubRepo>> response) {
                Log.d("retrofit resp", response.body().get(0).getName());
                //已经回掉到主线程了
            }

            @Override
            public void onFailure(Call<List<GitHubRepo>> call, Throwable t) {
                //已经回掉到主线程了
                Log.d("MainActivity", "onfail");
            }
        });
    }

    /**
     * retrofit和rxjava的结合
     */
    private void doRetroRequestWithRxJava() {
//        ServiceGenerator.createService(GitHubClient.class).reposForUserRx("fs-opensource").subscribeOn(Schedulers.io()).
//                observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<GitHubRepo>>() {
//            @Override
//            public void accept(List<GitHubRepo> gitHubRepos) throws Exception {
//                for (GitHubRepo repo : gitHubRepos) {
//                    Log.d("rx retro", "id:" + repo.getId());
//                }
//            }
//        });
        ServiceGenerator.createService(GitHubClient.class).reposForUserRx("fs-opensource").subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).flatMap(new Function<List<GitHubRepo>, ObservableSource<GitHubRepo>>() {
            @Override
            public ObservableSource<GitHubRepo> apply(List<GitHubRepo> gitHubRepos) throws Exception {
                return Observable.fromIterable(gitHubRepos);
            }
        }).subscribe(new Consumer<GitHubRepo>() {
            @Override
            public void accept(GitHubRepo gitHubRepo) throws Exception {
                Log.d("rx retro", "id:" + gitHubRepo.getId());
            }
        });
    }


    /**
     * rxjava的变换 不完整的subscriber
     */
    private void doRx3() {
//        Observable.just(1, 2, 3, 4).subscribe(new Consumer<Integer>() {
//            @Override
//            public void accept(Integer i) throws Exception {
//                Log.d("consumer:", i + "");
//            }
//        });

        Observable.just(1, 2, 3, 4).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer i) throws Exception {
                Log.d("consumer:", i + "");
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.d("consumer:", throwable.getMessage());
            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                Log.d("action:", "on complete");
            }
        });
    }

    /**
     * rxjava 的转换
     */
    private void doRx4() {
        Observable.just(R.mipmap.ic_launcher).map(new Function<Integer, Bitmap>() {
            @Override
            public Bitmap apply(Integer i) throws Exception {
                return BitmapFactory.decodeResource(getResources(), i);
            }
        }).subscribe(new Consumer<Bitmap>() {
            @Override
            public void accept(Bitmap bitmap) throws Exception {
                iv.setImageBitmap(bitmap);
            }
        });
    }

    /**
     * rxjava的线程切换2
     */
    private void doRx7() {
        Observable.just(1, 2, 3, 4).subscribeOn(Schedulers.io()).doOnDispose(new Action() {
            @Override
            public void run() throws Exception {
                Log.d("rxjava 7 thread id", Thread.currentThread().getId() + "");
            }
        }).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.d("rxjava 7", integer + "");
                    }
                });
    }
}
